<template>
  <div>
    <div class="stepBox">
      <div class="topBox">
        <span></span>
        <div>
          <el-button
            v-if="active"
            class="btnList"
            @click="back"
          >取消</el-button>
          <el-button
            v-if="active"
            type="primary"
            class="btnList"
            @click="next"
          >下一步</el-button>
          <el-button
            v-if="!active"
            type="primary"
            class="btnList"
            :loading="submitLoading"
            @click="save"
          >保存</el-button>
          <el-button
            v-if="!active"
            class="btnList"
            @click="last"
          >上一步</el-button>
        </div>
      </div>
      <el-divider />
      <!-- 步骤条 -->
      <div class="stepsColor common">
        <div class="stepsOne common">
          <div :class="active ? 'one_class common' : 't_class common'">1</div>
          <div :class="active ? 'two_class' : 'w_class'">基本属性&商品描述</div>
        </div>
        <div class="line"></div>
        <div class="stepsTwo common">
          <div :class="active ? 't_class common' : 'one_class common'">2</div>
          <div :class="active ? 'w_class' : 'two_class'">基本属性&商品描述</div>
        </div>
      </div>
    </div>
    <!-- 商品 -->
    <div class="addCom common">
      <div v-if="active">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-card class="leftCom">
            <el-form-item label="商品名称" prop="productName">
              <el-input
                v-model.trim="form.productName"
                type="textarea"
                rows="2"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="卖点简介">
              <el-input
                v-model.trim="form.productBrief"
                type="textarea"
                rows="2"
                show-word-limit
              />
            </el-form-item>
            <el-form-item v-if="detailsImgsList" label="商品详情">
              <DraggableImageUpload v-model="detailsImgsList" :limit="20" />
            </el-form-item>
            <el-form-item v-else label-width="0">
              <WangEditor v-model="form.productText" />
            </el-form-item>
            <el-form-item label="商品参数">
              <Parameter ref="parameterRef" v-model="form.parameterList" :product-id="productId" />
            </el-form-item>
          </el-card>
          <el-card class="rightCom">
            <el-form-item label="官方分类" prop="classifyId">
              <el-cascader
                v-model="form.classifyId"
                :options="classifyList"
                clearable
                filterable
                :props="{
                  checkStrictly: false,
                  label: 'categoryName',
                  value: 'id',
                  children: 'childs',
                }"
              />
            </el-form-item>

            <el-form-item label="商品分组" prop="shopGroupId">
              <el-select
                v-model="form.shopGroupId"
                placeholder="请选择商品分组"
                clearable
                filterable
                :remote-method="selectedRemoteMethod"
                :loading="selectedLoading"
              >
                <el-option
                  v-for="(item, index) in groupList"
                  :key="index"
                  :label="item.groupName"
                  :value="item.shopGroupId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="品牌">
              <el-select
                v-model="form.brandId"
                clearable
                placeholder="请选择品牌"
              >
                <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  :label="item.brandName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item class="form-item-long" label="供应商">
              <el-input
                v-model="form.supplierName"
                maxlength="20"
                show-word-limit
                placeholder="请输入供应商名称"
              />
            </el-form-item>
            <el-form-item label="需要物流" prop="ifLogistics">
              <el-radio-group v-model="form.ifLogistics">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="上架状态" prop="shelveState">
              <el-radio-group v-model="form.shelveState">
                <el-radio :label="1">上架</el-radio>
                <el-radio :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="允许超卖" prop="ifOversold">
              <el-radio-group v-model="form.ifOversold">
                <el-radio :label="1">允许</el-radio>
                <el-radio :label="0">不允许</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="积分兑换" prop="ifCredit">
              <el-radio-group v-model="form.ifCredit">
                <el-radio :label="1">允许</el-radio>
                <el-radio :label="0">不允许</el-radio>
              </el-radio-group>
              <p style="color: #cf0f0f">
                开启积分兑换后，积分所抵扣的金额由商户承担
              </p>
            </el-form-item>
            <el-form-item
              v-if="form.ifCredit"
              class="form-item-long"
              label="单笔最大抵扣"
              prop="creditLimit"
            >
              <el-input-number
                v-model="form.creditLimit"
                :controls="false"
                :max="999999999"
                :min="0"
                :precision="0"
                placeholder="请输入单笔最大抵扣"
              />
              <p
                style="
                  color: #cf0f0f;
                  line-height: 25px;
                  margin-top: 10px;
                "
              >
                限制一笔订单中该商品最多抵扣多少积分
              </p>
              <p style="color: #cf0f0f;line-height: 25px">
                ( 注：1积分 = {{ integralProportion }}元 请输入整数 )
              </p>
            </el-form-item>
            <!--            <el-form-item label="花呗分期">-->
            <!--              <el-radio-group v-model="form.ifHuabei">-->
            <!--                <el-radio :label="1">支持</el-radio>-->
            <!--                <el-radio :label="0">不支持</el-radio>-->
            <!--              </el-radio-group>-->
            <!--            </el-form-item>-->
          </el-card>
        </el-form>
      </div>
      <div v-if="!active" class="centerCom">
        <el-form ref="paramsRef" :model="params">
          <StyleInformation :form="params" />
        </el-form>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog
      v-model="visible.image"
      class="check-image-dialog"
      title="查看图片"
      center="center"
    >
      <img width="100%" :src="detailImg" alt />
    </el-dialog>
  </div>
</template>

<script setup>
import { defineComponent, onBeforeMount, reactive, ref, shallowRef, toRefs } from 'vue'
import {
  getGroupSelect,
  getClassify,
  getClassifyAdd,
  getClassifyGetById,
  getClassifyUpdate,
  getBrandList,
} from '@/api/commodity'
import { getSelect } from '@/api/account'
import StyleInformation from './addComponent.vue'
import { WangEditor } from '@/components/Wangeditor/index.js';
import Parameter from '@/components/commodity/parameter.vue';
import DraggableImageUpload from '@/components/Upload/DraggableImageUpload/index.vue'

/**
 * @typedef {import('./types').ProductForm} ProductForm
 */

defineComponent({
  name: 'CommodityForm'
})

const props = defineProps({
  productId: {
    type: Number,
    default: 0,
  }
})
const submitLoading = ref(false)
const btnType = ref()
const detailsImgsList = ref([])
let { productId } = toRefs(props);

const emit = defineEmits(['cancel'])

function initForm (data) {
  return {
    brandId: data && data.brandId || null,
    productName: data && data.productName || '',
    productBrief: data && data.productBrief || '',
    shopGroupId: data && data.shopGroupId || '',
    classifyId: data && data.classifyId || '',
    classifyLevel: data && data.classifyLevel || '',
    supplierName: data && data.supplierName || '',
    ifLogistics: data && data.ifLogistics || 0,
    shelveState: data && data.shelveState || 0,
    ifOversold: data && data.ifOversold || 0,
    ifCredit: data && data.ifCredit || 0,
    creditLimit: data && data.creditLimit || 0,
    ifHuabei: data && data.ifHuabei || 1,
    productText: data && data.productText || '',
    images: data && data.images || [],
    deletes: data && data.images || [],
    names: data && data.names || [
      {
        code: '',
        skuName: '',
        values: [
          {
            valueCode: '',
            skuValue: '',
            image: '',
          },
        ],
      },
    ],
    skus: data && data.skus || [
      {
        skuName: '',
        skuValue: '',
        price: '',
        originalPrice: '',
        stockNumber: '',
        weight: '',
        skuImage: '',
        style: '',
      },
    ],
  }
}
function initParams (data) {
  return {
    applyPrice: data && data.applyPrice || 0,
    attrStyle: data && data.attrStyle || 0,
    categoryId: data && data.categoryId || '',
    oversold: data && data.oversold || 1,
    collects: data && data.collects || 0,
    groupId: data && data.groupId || '',
    imgs: data && data.imgs || [],
    deletes: data && data.deletes || [],
    isDelete: data && data.isDelete || 0,
    limitCount: data && data.limitCount || 0,
    minusStock: data && data.minusStock || '',
    needLogistics: data && data.needLogistics || 1,
    platform: data && data.platform || '',
    price: data && data.price || 0,
    productCode: data && data.productCode || '',
    productName: data && data.productName || '',
    sellCount: data && data.sellCount || 0,
    sellDesc: data && data.sellDesc || '',
    sellType: data && data.sellType || '',
    shortName: data && data.shortName || '',
    skuAttrList: data && data.skuAttrList || [
      {
        code: '',
        skuName: '',
        needImg: false,
        values: [
          {
            skuValue: '',
            valueCode: '',
            image: '',
          },
        ],
      },
    ],
    skuList: data && data.skuList || [
      {
        isDelete: '',
        skuAttrCodeDTOList: [
          {
            code: '',
            valueCode: '',
          },
        ],
        skuAttrList: [],
        sku: '',
        skuImg: '',
        price: 0,
        originalPrice: 0,
        stockNumber: 0,
        weight: 0,
      },
    ],
    sortOrder: data && data.sortOrder || '',
    status: data && data.status || '',
    stock: data && data.stock || '',
    supplierName: data && data.supplierName || '',
    views: data && data.views || '',
    weight: data && data.weight || '',
  }
}

const formRef = ref()
const paramsRef = ref()
const parameterRef = ref()
/**
 * form
 * @type {ProductForm}
 */
let form = ref({})
form.value = initForm()

const rules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
  ],
  shopGroupId: [
    { required: true, message: '请选择商品分组', trigger: 'change' },
  ],
  classifyId: [
    { required: true, message: '请选择商品分类', trigger: 'change' },
  ],
  ifLogistics: [
    { required: true, message: '请选择是否需要物流', trigger: 'change' },
  ],
  shelveState: [
    { required: true, message: '请选择是否上架', trigger: 'change' },
  ],
  ifOversold: [
    { required: true, message: '请选择是否允许超卖', trigger: 'change' },
  ],
  ifCredit: [
    {
      required: true,
      message: '请选择是否支持积分兑换',
      trigger: 'change',
    },
  ],
  creditLimit: [
    { required: true, message: '请输入单笔最大抵扣', trigger: 'blur' },
  ],
}

let params = ref({})
params.value = initParams();

/** 页面总visible */
let visible = reactive({
  image: false,
})

let active = shallowRef(1);

/** 品牌数据 */
let brandList = ref([]);
function getBrandListData () {
  getBrandList().then(res => {
    brandList.value = res.data
  })
}
// let integralList = ref([]);
/** 积分兑换金额比例 */
let integralProportion = shallowRef('');
function getCredit () {
  getSelect({ dictName: 'CREDIT_CONFIG' }).then(res => {
    // integralList.value = res.data
    res.data.forEach((item) => {
      if (item.dictName === 'credit_exchange_rate') {
        integralProportion.value = item.dictDescribe
      }
    })
  })
}

let imgList = ref([]);
let detailImg = shallowRef('');

// 封装验证函数
function submitForm () {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid) => {
      console.log(valid, 'valid')
      if (valid) {
        resolve()
      } else {
        reject(new Error('错误'))
      }
    })
  })
}

// 下一步
function next () {
  if (active.value === 1) {
    let parameterSubmitForm = parameterRef.value.submitForm()
    Promise.all([submitForm(), parameterSubmitForm])
      .then((res) => {
        console.log(res, 'res')
        // 验证成功后在此处发请求
        active.value = 0
        sessionStorage.setItem(
          'form', JSON.stringify(form.value.skus)
        )
      }).catch(() => {
        ElMessage.warning('请填写正确的信息!')
        return false
      })
  } else {
    formRef.value.validate((valid) => {
      if (!valid) {
        ElMessage.warning('请填写正确的信息!')
        return false
      }
    })
  }
}
// 点击新增商品时表单数据重置
function reset () {
  imgList.value = []
  detailImg.value = ''
  visible.image = false
  active.value = 1
  form.value = initForm()
  params.value = initParams()
  formRef.value?.resetFields()
  paramsRef.value?.resetFields()
  detailsImgsList.value = []
}
// 返回
function back () {
  active.value = 1
  emit('cancel')
}
// 上一步
function last () {
  if (active.value !== 1) {
    active.value = 1
  }
}
// 保存
function save () {
  console.log(params.value, 'params')
  // 图片
  for (let i = 0; i < params.value.imgs.length; i++) {
    if (params.value.imgs[i] === '') {
      ElMessage.warning('请上传商品图片!')
      return false
    }
  }
  if (params.value.attrStyle === 1) {
    // 多规格
    for (let i = 0; i < params.value.skuAttrList.length; i++) {
      if (params.value.skuAttrList[i].skuName === '') {
        ElMessage.warning('规格名不能为空!')
        return false
      }
      if (params.value.skuAttrList[i].values.length === 0) {
        ElMessage.warning('请填写规格值!')
        return false
      } else {
        for (let j = 0; j < params.value.skuAttrList[i].values.length; j++) {
          if (params.value.skuAttrList[i].values[j].skuValue === '') {
            ElMessage.warning('规格值不能为空!')
            return false
          }
        }
      }
    }
    for (let i = 0; i < params.value.skuList.length; i++) {
      if (!params.value.skuList[i].price) {
        ElMessage.warning('价格不能为空!')
        return false
      }
      if (!params.value.skuList[i].originalPrice) {
        ElMessage.warning('原价不能为空!')
        return false
      }
      if (params.value.skuList[i].price > params.value.skuList[i].originalPrice) {
        ElMessage.warning('价格不能大于原价!')
        return false
      }
      if (!params.value.skuList[i].stockNumber) {
        ElMessage.warning('库存不能为空!')
        return false
      }
    }
  } else {
    // 单规格
    params.value.skuAttrList = params.value.skuAttrList.slice(0, 1)
    params.value.skuList = params.value.skuList.slice(0, 1)
    params.value.skuAttrList[0].values = params.value.skuAttrList[0].values.slice(0, 1)
    if (params.value.skuAttrList[0].values[0].skuValue === '') {
      ElMessage.warning('规格值不能为空!')
      return false
    }
    const curSku = params.value.skuList[0]
    console.log(curSku, 'curSku')
    if (!curSku.price) {
      ElMessage.warning('价格不能为空!')
      return false
    }
    if (!curSku.originalPrice) {
      ElMessage.warning('原价不能为空!')
      return false
    }
    if (curSku.price > curSku.originalPrice) {
      ElMessage.warning('价格不能大于原价!')
      return false
    }
    if (!curSku.stockNumber) {
      ElMessage.warning('库存不能为空!')
      return false
    }
  }
  form.value.names = params.value.skuAttrList
  params.value.skuList.forEach((element) => {
    element.style = params.value.attrStyle
  })
  form.value.skus = params.value.skuList
  form.value.images = params.value.imgs.map(v => { return { imgPath: v.url } })
  form.value.deletes = params.value.deletes
  if (detailsImgsList.value) {
    form.value.productText = detailsImgsList.value.map(v => v.url)?.join('\n');
  }
  form.value.classifyId = Array.isArray(form.value.classifyId)
    ? form.value.classifyId[form.value.classifyId.length - 1]
    : form.value.classifyId
  if (productId.value && btnType.value === 'edit') {
    form.value.productId = productId.value
    const sku = JSON.parse(sessionStorage.getItem('form'))
    sku.forEach((element, i) => {
      for (let index = 0; index < form.value.skus.length; index++) {
        if (i === index) {
          form.value.skus[index].skuId = element.skuId
        }
      }
    })
    submitLoading.value = true
    getClassifyUpdate(form.value).then(res => {
      if (res.code === '') {
        ElMessage.success('成功!')
        back()
        reset()
      }
    }).finally(() => {
      submitLoading.value = false
    })
  } else if (btnType.value === 'copy') {
    const sku = JSON.parse(sessionStorage.getItem('form'))
    sku.forEach((element, i) => {
      for (let index = 0; index < form.value.skus.length; index++) {
        if (i === index) {
          form.value.skus[index].skuId = element.skuId
        }
      }
    })
    submitLoading.value = true
    getClassifyUpdate(form.value).then(res => {
      if (res.code === '') {
        ElMessage.success('成功!')
        back()
        reset()
      }
    }).finally(() => {
      submitLoading.value = false
    })
  } else {
    submitLoading.value = true
    getClassifyAdd(form.value).then(res => {
      if (res.code === '') {
        ElMessage.success('成功!')
        back()
        reset()
      }
    }).finally(() => {
      submitLoading.value = false
    })
  }
}

/**
 * *******************************************************
 * ************************ 商品详情  *********************
 * *******************************************************
 */

/** 商品分组 */
let groupList = ref([]);
let groupOptions = ref([]);
let selectedLoading = ref(false);
function groups () {
  getGroupSelect({}).then(res => {
    groupList.value = res.data
    groupOptions.value = res.data
  })
}
/** 远程搜索 */
const selectedRemoteMethod = (query) => {
  if (query) {
    selectedLoading.value = true
    setTimeout(() => {
      selectedLoading.value = false
      groupOptions.value = groupList.value.filter((item) => {
        return item.label.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  } else {
    groupOptions.value = []
  }
}

/** 官方分类 */
let classifyList = ref([]);
function selectList () {
  getClassify().then(res => {
    classifyList.value = filterList(res.data)
  })
}

// 获取详情
function details (type) {
  btnType.value = type
  getClassifyGetById({ productId: productId.value }).then(res => {
    form.value = res.data
    form.value.productText = res.data.productText
    if (form.value.productText.indexOf('http') === 0) {
      detailsImgsList.value = form.value.productText.split('\n').map(v => {
        return {
          url: v
        }
      });
    } else {
      detailsImgsList.value = null
    }
    if (res.data.names.length !== 0) {
      params.value.skuAttrList = res.data.names
    }
    params.value.skuList = form.value.skus
    params.value.attrStyle = res.data.skus[0]?.style
    params.value.imgs = res.data.images.map(v => {
      return {
        url: v.imgPath
      }
    })
  })
}

function filterList (data) {
  data.forEach((i) => {
    if (i.childs.length) {
      filterList(i.childs)
    } else {
      i.childs = null
    }
  })
  return data
}

function filterObject (template, source) {
  // 创建新对象来存储过滤后的值
  const result = {};

  // 遍历模板对象的键
  for (const key in template) {
    if (Object.prototype.hasOwnProperty.call(template, key)) {
      if (source[key] !== undefined) { // 判断 source 是否有对应的键
        // 判断是否是对象，如果是则递归处理
        if (typeof template[key] === 'object' && !Array.isArray(template[key])) {
          result[key] = filterObject(template[key], source[key]);
        } else if (Array.isArray(template[key]) && template[key].length > 0 && typeof template[key][0] === 'object') {
          // 如果是数组并且数组第一项是对象的情况（比如 images）
          result[key] = source[key].map(item => filterObject(template[key][0], item));
        } else {
          result[key] = source[key]; // 对应字段直接赋值
        }
      }
    }
  }

  return result;
}

defineExpose({
  last,
  reset,
  details
})

onBeforeMount(() => {
  groups()
  selectList()
  getBrandListData()
  // if (this.productId) {
  //   this.details()
  // }
  getCredit()
})
// export default {
//   watch: {
//     productId: {
//       handler (nVal, oVal) {
//         if (nVal) {
//           // this.details()
//         }
//       },
//     },
//   },
// }
</script>

<style lang="scss" scoped>
.stepBox {
  .topBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.btnList {
  width: 100px;
  height: 38px;
}
.addTitle {
  font-size: 20px;
  color: #333333;
  line-height: 50px;
}
.stepsColor {
  font-size: 20px;
  line-height: 40px;
  padding: 20px 0;
  margin-bottom: 20px;
  .one_class {
    width: 40px;
    background: #3a68f2;
    border-radius: 50%;
    color: #ffffff;
    margin: 0 10px;
  }
  .two_class {
    color: #3a68f2;
  }
  .line {
    width: 230px;
    height: 2px;
    background: #e0e5eb;
    margin: 0 20px;
  }
  .t_class {
    width: 40px;
    background: #dddddd;
    border-radius: 50%;
    color: #333333;
    margin: 0 10px;
  }
  .w_class {
    color: #666666;
  }
}
.common {
  display: flex;
  justify-content: center;
  align-items: center;
}

.addCom {
  justify-content: space-around;
  align-items: unset;
  &>div {
    width: 100%;
  }
  .el-form {
    display: flex;
  }
  .leftCom {
    width: 65%;
    background: #ffffff;
  }
  .rightCom {
    // width: 35%;
    flex: 1;
    background: #ffffff;
    margin-left: 20px;
  }
}
// .centerCom {
//   width: 1660px;
//   background: #ffffff;
//   box-shadow: 0px 5px 20px 0px rgba(51, 51, 51, 0.15);
//   border-radius: 4px;
// }
</style>

<style scoped>
.form-item-long :deep(.el-input){
  width: 100%;
}
</style>
